package base;

import java.util.ArrayList;

public class Sql {
	/**
	 * 创建查询sql语句 示例 ArrayList<String> list = new ArrayList<String>();
	 * list.add("07"); list.add(""); list.add("0");
	 * createSql("INSERT",'teacher',list); 数据需要一一对应完整
	 * 
	 * @param operation INSERT操作
	 * @param table     表名
	 * @param list      INSERT的数据
	 * @return string or null
	 */
	public static String createSql(String operation, String table, ArrayList<String> list) {

		StringBuilder sql = new StringBuilder();
		if ("INSERT".equals(operation)) {
			/**
			 * createSql("INSERT",'teacher',('00002', '李雷', '111', '119')); 最终生成的SQL语句可能是：
			 * INSERT INTO `teacher` VALUES ('00002', '李雷', '111', '119')
			 */
			sql.append("INSERT INTO ");
			sql.append(table);
			sql.append(" VALUES (");
			for (String string : list) {
				if ("".equals(string)) {
					sql.append("null,");
				} else {
					sql.append("'" + string + "',");
				}
			}
			sql.deleteCharAt(sql.length() - 1);
			sql.append(")");
		}
		return sql.toString();
	}

	/**
	 * 创建更新数据sql语句 示例 createSql("UPDATE",'teacher',"'id' = 1","'name'='123'");
	 * 
	 * @param operation 操作
	 * @param table     表名
	 * @param condition 条件
	 * @param data      更新的数据内容
	 * @return
	 */
	public static String createSql(String operation, String table, String condition, String data) {

		StringBuilder sql = new StringBuilder();

		if ("UPDATE".equals(operation)) {
			/**
			 * createSql("UPDATE",'teacher',"'id' = 1","'name'='123'"); 实际生成的SQL语句可能是：
			 * UPDATE `think_user` SET `name`='123' WHERE `id` = 1
			 */
			sql.append("UPDATE ");
			sql.append(table);
			sql.append(" SET ");
			sql.append(data);
			sql.append(" WHERE ");
			sql.append(condition);
		}

		return sql.toString();
	}

	/**
	 * 创建查询或删除sql语句 示例 createSql("SELECT",'teacher',"'id' = 1");
	 * createSql("DELETE",'teacher',"'id' = 1");
	 * 
	 * @param operation 操作
	 * @param table     表名
	 * @param condition 条件
	 * @return null or String
	 */
	public static String createSql(String operation, String table, String condition) {

		StringBuilder sql = new StringBuilder();

		if ("SELECT".equals(operation)) {
			/**
			 * createSql("SELECT",'teacher',"'id' = 1"); 最终生成的SQL语句可能是： SELECT * FROM
			 * `think_user` WHERE `id` = 1
			 */
			sql.append("SELECT * FROM ");
			sql.append(table);
			sql.append(" WHERE ");
			sql.append(condition);
		}

		if ("DELETE".equals(operation)) {
			/**
			 * createSql("DELETE",'teacher',"'id' = 1"); 实际生成的SQL语句可能是： DELETE FROM
			 * `think_user` WHERE `id` = 1
			 */
			sql.append("DELETE FROM ");
			sql.append(table);
			sql.append(" WHERE ");
			sql.append(condition);
		}
		return sql.toString();
	}

}
